import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth/next'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

export async function POST(
  request: NextRequest,
  { params }: { params: { id: string; submissionId: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    
    if (!session?.user) {
      return NextResponse.json({ message: '未授权访问' }, { status: 401 })
    }

    // 只有教师和管理员可以评分
    if (session.user.role !== 'TEACHER' && session.user.role !== 'ADMIN') {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    const { score } = await request.json()

    if (typeof score !== 'number' || score < 0 || score > 100) {
      return NextResponse.json({ message: '分数必须在0-100之间' }, { status: 400 })
    }

    const experimentId = params.id
    const submissionId = params.submissionId

    // 验证实验是否存在以及教师是否有权限
    const experiment = await prisma.experiment.findUnique({
      where: { id: experimentId },
      include: { createdBy: true }
    })

    if (!experiment) {
      return NextResponse.json({ message: '实验不存在' }, { status: 404 })
    }

    // 检查权限：实验创建者或管理员
    if (session.user.role !== 'ADMIN' && experiment.createdBy.id !== session.user.id) {
      return NextResponse.json({ message: '您没有权限评分此实验' }, { status: 403 })
    }

    // 验证提交是否存在
    const submission = await prisma.experimentSubmission.findUnique({
      where: { 
        id: submissionId,
        experimentId: experimentId
      },
      include: {
        student: {
          select: { id: true, name: true, email: true }
        }
      }
    })

    if (!submission) {
      return NextResponse.json({ message: '提交记录不存在' }, { status: 404 })
    }

    // 更新提交的总分和状态
    const updatedSubmission = await prisma.experimentSubmission.update({
      where: { id: submissionId },
      data: {
        score: score,
        status: 'GRADED'
      },
      include: {
        student: {
          select: { id: true, name: true, email: true }
        },
        experiment: {
          select: { id: true, title: true }
        }
      }
    })

    return NextResponse.json({
      message: '评分成功',
      submission: updatedSubmission
    })

  } catch (error) {
    console.error('快速评分错误:', error)
    return NextResponse.json(
      { message: '服务器内部错误' },
      { status: 500 }
    )
  }
} 